<template>
  <div>
    <el-dialog
      v-model="createVisible"
      :title="operation == 'create' ? '添加管理员' : '编辑管理员'"
      @before-ok="createOk"
      @close="close(createRef)"
      width="800px"
      top="100px"
    >
      <div style="width: 650px">
        <el-form
          :model="createForm"
          ref="createRef"
          :rules="createRules"
          label-width="120px"
          size="default"
          v-loading="createLoading"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="账号：" prop="account">
                <el-input
                  v-model="createForm.account"
                  placeholder="请输入账号"
                ></el-input>
              </el-form-item>
              <el-form-item label="姓名：" prop="real_name">
                <el-input
                  v-model="createForm.real_name"
                  placeholder="请输入姓名"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="头像：" prop="avatar">
                <upload-btn v-model="createForm.avatar" count="1"></upload-btn>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="角色：" prop="roles" v-if="adminLevel">
                <el-select
                  v-if="adminLevel"
                  v-model="createForm.roles"
                  multiple
                  placeholder="选择角色"
                  class="form-select-fil"
                  @change="$forceUpdate()"
                >
                  <el-option
                    v-for="item in roleSelect"
                    :key="item.id"
                    :label="item.role_name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="角色：" v-else>
                <div>超级管理员</div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码：" prop="pwd">
                <el-input
                  v-model="createForm.pwd"
                  type="password"
                  placeholder="请输入密码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="确定密码：" prop="conf_pwd">
                <el-input
                  v-model="createForm.conf_pwd"
                  type="password"
                  placeholder="请再次输入密码"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <span class="flex center">
          <el-button @click="createVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="createOk(createRef)"
            :loading="btnLoading"
            :disabled="btnLoading"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
<script lang="ts">

export default {
  name:'systemAdminCreate'
}

</script>
  <script lang="ts" setup>
import { ref, getCurrentInstance, nextTick, reactive, onMounted } from "vue";
import { useConfig } from "@/store";
import { create, update, getDetail } from "@/api/system/admin";
import { getRoleSelectList } from "@/api/system/role";

import type { CommonProps, FormInstance, FormRules } from "element-plus";
import type { Result, ResultError } from "@/types";

const {
  proxy: { $utils },
} = getCurrentInstance() as any;

const emit = defineEmits(["success"]);

const operation = ref("create");

const operationId = ref(0);

const adminLevel = ref<number>(1)

const createVisible = ref(false);

const createRef: any = ref<typeof FormInstance>();

const createForm = ref({
  account: "",
  real_name: "",
  avatar: "",
  roles: "",
  pwd: "",
  conf_pwd: "",
});

const createRules: any = reactive({
  account: [{ required: true, message: "账号不能为空！" , trigger: 'blur'}],
  real_name: [{ required: true, message: "姓名不能为空！" , trigger: 'blur'}],
  avatar: [{ required: true, message: "请上传头像" , trigger: 'change'}],
  roles: [{ required: true, message: "请选择角色" , trigger: 'change'}],
  // pwd: [{ required: true, message: "请输入密码" }],
  // conf_pwd: [{ required: true, message: "请再次密码" }],
});

const createLoading: any = ref(false);

const toInit = () => {
  if (!operationId.value) {
    return;
  }
  createLoading.value = true;
  getDetail({ id: operationId.value })
    .then((res) => {
      createForm.value.account = res.data.account;
      createForm.value.real_name = res.data.real_name;
      createForm.value.avatar = res.data.avatar;
      createForm.value.roles = res.data.roles;
      adminLevel.value = res.data.level
      if(!adminLevel.value){
        createRules.roles = []
      }else{
        createRules.roles = [{ required: true, message: "请选择角色" , trigger: 'change'}]
      }
      createLoading.value = false;
    })
    .catch((res) => {
      $utils.errorMsg(res);
    });
};

const btnLoading = ref(false);

const createOk = async (formEl: typeof FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      console.log(createForm.value);
      if (btnLoading.value) {
        return;
      }
      btnLoading.value = true;
      let operationApi: any = null;
      if (operation.value == "create") {
        operationApi = create(createForm.value);
      } else {
        operationApi = update(
          Object.assign(
            {
              id: operationId.value,
            },
            createForm.value
          )
        );
      }
      operationApi
        .then((res: Result) => {
          $utils.successMsg(res.message);
          close(formEl);
          emit("success");
          btnLoading.value = false;
        })
        .catch((err: ResultError) => {
          $utils.errorMsg(err);
          btnLoading.value = false;
        });
    }
  });
};

const open = (id = 0) => {
  adminLevel.value = 1;
  if (id != 0) {
    operation.value = "update";
    operationId.value = id;
  } else {
    operation.value = "create";
    createRules['pwd'] = [{ required: true, message: "请输入密码" , trigger: 'blur'}];
    createRules['conf_pwd'] = [{ required: true, message: "请再次密码" , trigger: 'blur'}];
  }
  nextTick(() => {
    toInit();
  });
  createVisible.value = true;
};

const close = async (formEl: typeof FormInstance | undefined) => {
  if (formEl) {
    formEl.resetFields();
  }
  operationId.value = 0;
  createVisible.value = false;
  createRules.pwd = []
  createRules.conf_pwd = []
};

const roleSelect = ref<any>([]);

const initRoleSelect = () => {
  getRoleSelectList()
    .then((res: Result) => {
      roleSelect.value = res.data;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

onMounted(() => {
  initRoleSelect();
});

defineExpose({ open });
</script>